const http = require("http");
const qs = require("querystring");

// const postData = "{'username':'admin','password':'54321'}"
// const postData = "username=nimei&pwd=123456"
// const postData = qs.stringify({
//     username: "admin",
//     password: "123456",
// });

/* 构造请求携带的JSON数据 */
const postData = JSON.stringify({
    username: "admin",
    password: "123456",
});

const options = {
    hostname: "www.httpbin.org",
    // port: 80,
    path: "/post",

    // 声明是POST请求
    method: "POST",

    // 配置请求头
    headers: {
        // 请求携带的数据格式
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",

        // 计算请求数据的字节数
        "Content-Length": Buffer.byteLength(postData),
    },
};

const req = http.request(options, (res) => {
    let resData = "";
    let count = 0;

    res.on("data", (chunk) => {
        console.log(++count, chunk);
        resData += chunk;
    });

    res.on("end", () => {
        console.log("响应完毕", resData);
    });

    // 监听响应的错误事件
    res.on("error", (err) => {
        console.log("res err=", err);
    });
});

req.on("error", (err) => {
    console.log("req err=", err);
});

// 在请求对象中携带数据
req.write(postData);

// 请求发送完毕
req.end();
